let id = location.href.split("?")[1]
function for_res(res)
{
    $('.tr').remove()
    res.forEach(item => {
        let html=`
        <tr class="tr">
        <td>${item.id}</td>
        <td>${item.headline}</td>
        <td>${item.abstract}</td>
        <td>${item.content}</td>
        <td>${item.classify}</td>
        <td>${item.author}</td>
        <td>${item.createdAt}</td>
        <td>
        <input type="button" value="编辑" onclick="update(${item.id})">
        <input type="button" value="删除" onclick="del(${item.id})">
        </td>
    </tr>
    `
    $('#tab').append(html)
    });
}

$(function()
{
    $.get('http://127.0.0.1:8000/user',function(res)
    {
        for_res(res)
    })
})

function find()
{
    let id = $('#find_text').val()
    $.get(`http://127.0.0.1:8000/user?id=${id}`,function(res)
    {
        for_res(res)
    })
}

function del(id)
{
    $.ajax({
        //data,
        type:'delete',
        url:`http://127.0.0.1:8000/delete/${id}`,
        success:function(res)
        {
            for_res(res)
        }
    })
}

function add()
{
    location.href='./save.html'
}

function update(id)
{
    
    location.href=`./save.html?${id}`
}

if(id)
{
    $.get(`http://127.0.0.1:8000/user?id=${id}`,function(res)
    {
        $('#name1').val(res[0].headline)
        $('#name2').val(res[0].abstract)
        $('#name3').val(res[0].content)
        $('#name4').val(res[0].classify)
        $('#name5').val(res[0].author)
    })
}


function save()
{
    let obj={
        headline:$('#name1').val(),
        abstract:$('#name2').val(),
        content:$('#name3').val(),
        classify:$('#name4').val(),
        author:$('#name5').val()
    }
    if(id)
    {
        obj.id=id
        $.ajax({
            data:obj,
            type:'put',
            url:`http://127.0.0.1:8000/put`,
            success:function(res)
            {
                location.href='./index.html'
            }
        })
    }else
    {
        $.post(`http://127.0.0.1:8000/post`,obj,function()
        {
            location.href='./index.html'
        })
    }
}

function cancel()
{
    location.href='./index.html'
}